#include "Avalon/SignalHandling/TaskSignalHandler.hpp"

using namespace Avalon;
using namespace Avalon::SignalHandling;
using namespace Avalon::Threading;
using namespace boost;
using namespace boost::signals2;
using namespace std;

TaskSignalHandler::TaskSignalHandler()
    : m_queuedSignalHandler(QueuedSignalHandler::Create()){
  m_task.SetSignalHandler(this);
}

TaskSignalHandler::~TaskSignalHandler() {
  Stop();
}

void TaskSignalHandler::Start() {
  boost::lock_guard<boost::mutex> lock(m_mutex);
  if(m_queuedConnection.connected()) {
    return;
  }
  m_queuedConnection = m_queuedSignalHandler->ConnectQueuedSignal(
    bind(&TaskSignalHandler::OnSignalsQueued, this));
}

void TaskSignalHandler::Stop() {
  boost::lock_guard<boost::mutex> lock(m_mutex);
  if(!m_queuedConnection.connected()) {
    return;
  }
  m_queuedConnection.disconnect();
  m_task.Wait();
}

void TaskSignalHandler::OnSignalsQueued() {
  m_task.Enqueue();
}

TaskSignalHandler::SignalHandlerTask::SignalHandlerTask() {}

TaskSignalHandler::SignalHandlerTask::~SignalHandlerTask() {}

void TaskSignalHandler::SignalHandlerTask::SetSignalHandler(
    TaskSignalHandler* signalHandler) {
  m_signalHandler = signalHandler;
}

void TaskSignalHandler::SignalHandlerTask::ProcessTask() {
  m_signalHandler->m_queuedSignalHandler->HandleSignals();
}
